package com.vikutorika.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class ParamUtil {
    private ParamUtil() {
    }
    public static <T> T paramToBean(HttpServletRequest request, Class<T> clazz) {
        Map<String, String> collect = request.getParameterMap().entrySet().stream().collect(
                Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0])
        );
        return BeanUtil.toBean(collect, clazz, CopyOptions.create().ignoreNullValue());
    }

    public static <T> T jsonToBean(HttpServletRequest req, Class<T> clazz) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // 处理异常
        }
        String requestBody = sb.toString();
        JSONObject jsonRequest = JSONUtil.parseObj(requestBody);

        return jsonRequest.toBean(clazz);
    }

}
